package com.bluetooth.temp;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.bluetooth.temp.adapter.OnlineRateAdapter;
import com.bluetooth.temp.bean.MonitorEntity;
import com.bluetooth.temp.util.DataUtil;
import com.bluetooth.temp.util.DateUtil;
import com.bluetooth.temp.util.ToastUtil;
import com.bluetooth.temp.view.RiseNumberTextView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OnlineActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = OnlineActivity.class.getSimpleName();
    private static final int REQUEST_SELECT_DEVICE = 1;

    private static final int UART_PROFILE_CONNECTED = 20;
    private static final int UART_PROFILE_DISCONNECTED = 21;
    private static final int STATE_OFF = 10;

    private int mState = UART_PROFILE_DISCONNECTED;

    RiseNumberTextView mTvTemp, mTvHum;
    TextView mTvConnectDevice;
    TextView mTvConnectStatus;
    ListView listView;
    OnlineRateAdapter adapter;

    BluetoothDevice mDevice;
    UartService mService;

    /**
     * 警报值
     */
    int warnValue = 100;

    final List<MonitorEntity> entities = new ArrayList<>();


    public static void start(Context context) {
        Intent starter = new Intent(context, OnlineActivity.class);
        context.startActivity(starter);
    }

    /**
     * 超过值，报警振动响铃，(当前正在响铃，则不报警)
     *
     * @param savedInstanceState
     */

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_online);

        initUI();
        initService();
    }

    /**
     * 蓝牙串口通讯GATT协议，连接设备的状态
     */
    private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            //*********************//
            if (UartService.ACTION_GATT_CONNECTED.equals(action)) {
                //已连接开发板
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Log.d(TAG, "UART_CONNECT_MSG");
                        if (TextUtils.isEmpty(mDevice.getName()) || "null".equals(mDevice.getName())) {
                            mTvConnectDevice.setText("当前连接：" + "未知设备");
                        } else {
                            mTvConnectDevice.setText("当前连接：" + mDevice.getName());
                        }
                        mTvConnectStatus.setText("已连接");
                        mState = UART_PROFILE_CONNECTED;
                    }
                });
            }

            //*********************//
            if (UartService.ACTION_GATT_DISCONNECTED.equals(action)) {
                //已断开与开发板的连接
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mTvConnectDevice.setText("当前连接：无");
                        mTvConnectStatus.setText("已断开");
//                        listAdapter.add("[" + currentDateTimeString + "] Disconnected to: " + mDevice.getName());
                        mState = UART_PROFILE_DISCONNECTED;
                        mService.close();
                    }
                });
            }


            //*********************//
            if (UartService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                mService.enableTXNotification();
            }

            //*********接收到蓝牙设备数据************//
            if (UartService.ACTION_DATA_AVAILABLE.equals(action)) {
                //接收到开发板数据

                final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
//                            String text = new String(txValue, "UTF-8");

                            String byte2Hex = DataUtil.byte2Hex(txValue);
//                            float tempValue = DataUtil.hexToFloat(byte2Hex);

                            MonitorEntity entity = new MonitorEntity();
                            //解析温度
                            entity.setTempValue(DataUtil.parseTempValue(byte2Hex));
                            //解析湿度
                            entity.setHumValue(DataUtil.parseHumValue(byte2Hex));
                            entity.setText(byte2Hex);
                            entity.setTime(DateUtil.dateToString(new Date()));

                            entities.add(entity);

                            // 设置数据
                            setMonitorValueText(mTvTemp, entity.getTempValue());
                            setMonitorValueText(mTvHum, entity.getHumValue());

                            adapter.notifyDataSetChanged();
                            listView.smoothScrollToPosition(entities.size() - 1);
                        } catch (Exception e) {
                            Log.e(TAG, e.toString());
                        }
                    }
                });
            }
            //*********************//
            if (UartService.DEVICE_DOES_NOT_SUPPORT_UART.equals(action)) {
//                showMessage("Device doesn't support UART. Disconnecting");
                ToastUtil.show("该蓝牙设备不支持UART");
                mService.disconnect();
            }
        }
    };


    private void initUI() {
        TextView tvTopTitleCenter = findViewById(R.id.tvTopTitleCenter);
        tvTopTitleCenter.setText("温湿度监测");

        mTvTemp = findViewById(R.id.tv_online_temp);
        mTvTemp.setText("0");
        mTvHum = findViewById(R.id.tv_online_hum);
        mTvHum.setText("0");

        mTvConnectDevice = findViewById(R.id.tv_connect_device);
        mTvConnectStatus = findViewById(R.id.tv_connect_status);
        mTvConnectDevice.setText("当前连接：无");
        mTvConnectStatus.setText("扫描");

        listView = findViewById(R.id.listView);
        listView.setAdapter(adapter = new OnlineRateAdapter(this, entities));

        findViewById(R.id.tvTopTitleLeft).setOnClickListener(this);
        findViewById(R.id.ll_scanner).setOnClickListener(this);
    }

    /**
     * 初始化心跳监测服务
     */
    private void initService() {
        Intent bindIntent = new Intent(this, UartService.class);
        bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

        LocalBroadcastManager.getInstance(this).registerReceiver(UARTStatusChangeReceiver,
                makeGattUpdateIntentFilter());
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART);
        return intentFilter;
    }

    //UART service connected/disconnected
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mService = ((UartService.LocalBinder) rawBinder).getService();
            Log.d(TAG, "onServiceConnected mService= " + mService);
            if (!mService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName classname) {
            ////     mService.disconnect(mDevice);
            mService = null;
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvTopTitleLeft:
                onBackPressed();
                break;
            case R.id.ll_scanner:
                Intent newIntent = new Intent(this, DeviceListActivity.class);
                startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
                break;
            default:
                break;
        }
    }

    private void setMonitorValueText(final RiseNumberTextView tvView, float data) {
        // 设置数据
        tvView.withNumber(data);
        // 设置动画播放时间
        tvView.setDuration(250);
        tvView.setOnUpdateListener(new RiseNumberTextView.RiseUpdateListener() {
            @Override
            public void onUpdate(String value) {
                tvView.setText(value);
            }

            @Override
            public void onEndFinish() {

            }
        });
        // 开始播放动画
        tvView.start();
    }

    /**
     * 接收设备列表页返回的蓝牙设备信息
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_SELECT_DEVICE:
                //When the DeviceListActivity return, with the selected device address
                if (resultCode == Activity.RESULT_OK && data != null) {
                    String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
                    //拿到蓝牙设备地址，通过系统API获取设备的详细信息
                    mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);

                    //显示当前连接设备的名称
                    if (TextUtils.isEmpty(mDevice.getName()) || "null".equals(mDevice.getName())) {
                        mTvConnectDevice.setText("当前连接：" + "未知设备");
                    } else {
                        mTvConnectDevice.setText("当前连接：" + mDevice.getName());
                    }
                    mTvConnectStatus.setText("正在连接...");
                    Log.d(TAG, "... onActivityResultdevice.address==" + mDevice + "mserviceValue" + mService);
                    mService.connect(deviceAddress);
                }
                break;
            default:
                Log.e(TAG, "wrong request code");
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (mState == UART_PROFILE_CONNECTED) {
            new AlertDialog.Builder(this).setTitle("提示")
                    .setMessage("当前已连接蓝牙设备，是否退出？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    })
                    .setNegativeButton("取消", null).show();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(UARTStatusChangeReceiver);
            unbindService(mServiceConnection);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        } finally {
            if (mService != null) {
                mService.stopSelf();
                mService = null;
            }
        }
    }
}
